<template>
    <div>
        <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
                <span>采购基本信息</span>
                <div style="float: right;">
                    <el-button size="small" @click="onClose">取 消</el-button>
                    <template v-if="rolesBtn.includes('purchaseSubmitCode')">
                        <el-button size="small" type="primary" @click="onFormSubmit">提交物资采购计划审核</el-button>
                    </template>
                </div>
            </div>
            <form-create v-model="form.fApi" :rule="form.rule" :option="form.option" @btn-pdf-click="uploadPdf"/>
            <input type="file" ref="pdfFile" @change="pdfChange" style="display: none;" />
          </el-card>
<!----------------------------------------------------------物资列表---------------------------------------------------------->
          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>物资信息</span>
              <el-button style="float: right;" size="small" type="primary" @click="loadListMaterial(false)">选择物资</el-button>
              <el-dialog :title="material.title" :visible.sync="material.visible" :before-close="closeMaterial" :width="material.width" append-to-body :close-on-click-modal="false">
                <form-create 
                v-model="material.fApi" 
                :rule="material.rule" 
                :option="material.option" 
                @btn-search-click="loadListMaterial(true)" 
                @btn-reset-click="resetMaterial"
                @btn-type1-change="function(val){return typeChange(val,'type2Id','material','2')}"
                @btn-type2-change="function(val){return typeChange(val,'type3Id','material','1')}"
                @btn-submit-click="materialSubmit"/>
                <el-alert v-if="tis" :title="tis" type="success" show-icon :closable="false"/>
                <el-table :data="material.tableData" :row-key="getRowKeys"
                @selection-change="handleSelectionChange"  ref="table" stripe>
                    <tr v-for="(item, index) in material.tableLabel" :key="index">
                        <el-table-column v-if="item.type==='checkbox'" :fixed="item.type==='checkbox'?'left':'none'" type="selection" width="55" :reserve-selection="true"></el-table-column>
                        <el-table-column v-else-if="item.type==='createTime'" :prop="item.prop" :label="item.label" :min-width="item.width" :formatter="formatTime"></el-table-column>
                        <el-table-column v-else-if="item.type==='normal'" :prop="item.prop" :label="item.label" :min-width="item.width"></el-table-column>
                    </tr>
                </el-table>
                <el-row>
                    <el-pagination
                        class="page-footer"
                        background
                        layout="total,prev,pager,next,sizes,jumper"
                        :total="material.total"
                        :page-sizes="[10,20,30,40,50]"
                        @current-change="handlePageChange"
                        @size-change="handleSizeChange"/>
                </el-row> 
              </el-dialog>
            </div>
<!----------------------------------------------- 物资分类 和 物资列表 --------------------------------------------------------->
            <table class="custom-table" style="margin-bottom:10px;">
                <tr v-for="(item,index) in otherMaterial.materialInfo" :key="item.id">
                    <td class="tr-title">分类名称</td><td>{{item.type1Name}}</td>
                    <td class="tr-title">分类合计预估价</td><td> {{item.priceTotal}}</td>
                    <td v-if="index===0" :rowspan="otherMaterial.materialInfo.length">预估合计：{{totalSumAll}}</td>
                </tr>
            </table>
            <el-table :key="keys" :data="otherMaterial.tableData" style="width: 100%;" ref="table2" stripe>
                <el-table-column prop="name" label="物资名称" width="200"></el-table-column>
                <el-table-column prop="type1Name" label="分类" width="140">
                    <template slot-scope="scope">
                        {{scope.row.type1Name}}
                    </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="applyNum" label="申请数量" width="140">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.applyNum" @change="function(val){return inputPrice(val,scope.row,1)}" :step="1" step-strictly size="mini" :min="1" :max="100000"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="estimatePrice" label="预估价" width="140">
                    <template slot-scope="scope">
                        <el-input-number v-model="scope.row.estimatePrice" @change="function(val){return inputPrice(val,scope.row,2)}" size="mini" :max="100000"></el-input-number>
                    </template>
                </el-table-column>
                <el-table-column prop="skuInfo" label="技术参数及规格要求">
                    <template slot-scope="scope">
                        <el-input v-model="scope.row.skuInfo" type="textarea"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="addOtherMaterial(scope.row)">新增</el-button>
                        <el-button type="danger" size="mini" @click="delOtherMaterial(scope.row,scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
          </el-card>
<!----------------------------------------------------处理人---------------------------------------------------->
          <el-card class="box-card" shadow="hover">
            <div slot="header" class="clearfix">
              <span>分配转交人</span>
              <el-button style="float: right;" size="small" type="primary" @click="workflowOpen">选择转交人员</el-button>
            </div>
            <el-dialog :title="workflow.title" :visible.sync="workflow.visible" :width="workflow.width" append-to-body :close-on-click-modal="false">
              <el-radio-group v-model="workflow.handleUser">
                  <el-radio v-for="item in workflow.workflowList" :border="true" :key="item.id" :label="item.id">
                   {{item.name}}
                  </el-radio>
              </el-radio-group>
              <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="workflow.visible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="submitWorkflow">保存</el-button>
              </div>
            </el-dialog>
            <el-descriptions border>
              <el-descriptions-item label="转交步骤">内勤评审</el-descriptions-item>
              <el-descriptions-item label="转交人员">{{workflow.applyUser}}</el-descriptions-item>
            </el-descriptions>
          </el-card>
           
    </div>
</template>

<script>
    import store from '@/store'
    import moment from 'moment'
    import { arrayFormat } from "@/utils/index"
    import { 
        FORM_PURCHASE_PLAN,
        OPTION_INLINE,
        OPTION_BLOCK
    } from "@/views/purchase/purchaseModel/purchase_form"
    import { PARAMS_MATERIAL,LABEL_MATERIAL} from "@/config/common"
    import { uploads } from "@/api/common_api"
    import { getMaterialList } from "@/api/material_api"
    import { 
        purchaseApplyUser,
        purchaseSave
    } from "@/api/purchase_api"
    export default {
        props: ['row'],
        data() {
            return {
                form:{
                    fApi:{},
                    rule:FORM_PURCHASE_PLAN,
                    option:OPTION_BLOCK
                },
                //物资列表
                material:{
                    title:'选择物资',
                    width:"1400px",
                    visible:false,
                    fApi:{},
                    rule:PARAMS_MATERIAL,
                    option:OPTION_INLINE,
                    selection:[],
                    total:0,
                    tableData:[],
                    tableLabel: LABEL_MATERIAL
                },
                //物资统计--  统计列表 ，物资列表
                otherMaterial:{
                    materialInfo:[],
                    tableData:[]
                },
                workflow:{
                    title:'选择审核人',
                    width:"600px",
                    visible:false,
                    handleUser:'',//选择审核人
                    applyUser:'',//审核人
                    remarks:'',
                    workflowList:[]
                },
                tis:"",
                keys:0,//用于添加物资时更新列表
                params: {
                    type:"page",
                    pageNum: 1,
                    pageSize: 10
                },
                 //临时附件储存
                annxFileUrl:'',
            };
        },
        computed: {
            rolesBtn() {//按钮权限
                return this.$store.getters.permission_user.roles.length >=1 ? this.$store.getters.permission_user.roles[0].permissions:[];
            },
            totalSumAll(){//物资分类评估价合计
                let totalSumAll = 0;
                this.otherMaterial.materialInfo.map((item) => {
                    totalSumAll += parseFloat(item.priceTotal)
                })

                if((totalSumAll+'').indexOf(".") !== -1){
                   let str = totalSumAll.toString().split('.');
                   totalSumAll = str[1].length === 1 ? totalSumAll.toFixed(1) : totalSumAll.toFixed(2);
                }
                return totalSumAll;
                //return (totalSumAll+'').indexOf(".") !== -1 ? totalSumAll.toFixed(2) : totalSumAll;
            }
        },
        mounted(){
            this.initPorjectSelect();
        },
        methods: {
            //申请项目列表
            async initPorjectSelect(){
                const _project = await store.dispatch('user/getProjectSelect');
                const _roleList = arrayFormat(_project);
                this.form.fApi.updateRule('projectId', {
                    options: _roleList
                }, true);
                this.form.fApi.hidden(true,'name') //隐藏附件
                this.$nextTick(()=>{
                    this.form.fApi.setValue({
                        "projectId":"",
                        "startTime":"",
                        "applyTime":"",
                        "address":"",
                        "remarks":"",
                        "name":""
                    });
                });
            },
            formatTime(row, column) {
                const date = row[column.property];
                if (date == undefined) {
                return ''
                }
                return moment(date).format("YYYY-MM-DD  HH:mm:ss")
            },
            //上传pdf
            uploadPdf(){
                this.$refs.pdfFile.click();
            },
            async pdfChange(e){
                e.preventDefault();
                let _this = this;
                let file = e.target.files[0];
                if(file===undefined){return;}
                let fileArr = ['png','jpg','pdf'];
                let fileIndex= file.name.lastIndexOf(".");
                let _fileType = file.name.substr(fileIndex+1);
                if (!fileArr.includes(_fileType)) {
                    _this.$message.error("只支持文件后缀为png，jpg，pdf格式");
                    this.annxFileUrl = "";
                    e.target.value= "";
                    return;
                }
                let formData = new FormData();
                formData.append("resType",file);
                const {code,data} = await uploads('annxPDF',formData);
                if(code === 200){
                    this.annxFileUrl = data;//临时储存
                    this.form.fApi.setValue({"name":file.name});//传给后端
                    e.target.value = "";
                }
            },
             //物资相关操作  
            async loadListMaterial(openFlag){
                let params = {};
                 let formData = this.material.fApi;
                 if(Object.keys(formData).length > 0){
                    params = this.material.fApi.formData();
                 }
                if(!openFlag){ //选择
                    params.pageNum = this.params.pageNum;
                    params.pageSize = this.params.pageSize;
                    
                }else if(openFlag){//查询
                    params.pageNum = 1;
                    params.pageSize = 10;
                }
                const req = await getMaterialList(params);
                if(req.code === 200){
                    this.material.tableData = req.data.list;
                    this.material.tableData.forEach(v=>{
                        v.price = (v.price/100);
                    })
                    this.material.total = req.data.total;
                    /* this.$nextTick(()=>{
                        this.material.fApi.resetFields();
                    }); */
                    this.material.visible = true;
                    if(!openFlag){//弹出的时候初始化第一个分类的数据
                        this.typeChange(0,'type1Id','material','all');
                    }
                }
            },
            //物资三级分类查询
            async typeChange(val,field,type,flag){
                if(flag === 'all'){
                    this.$nextTick(()=>{
                        this[type].fApi.updateRule('type1Id', {options: []}, true);
                        this[type].fApi.updateRule('type2Id', {options: []}, true);
                        this[type].fApi.updateRule('type3Id', {options: []}, true);
                    })
                }else if(flag === '2'){
                    this.$nextTick(()=>{
                        this[type].fApi.updateRule('type2Id', {options: []}, true);
                        this[type].fApi.updateRule('type3Id', {options: []}, true);
                        this[type].fApi.setValue({'type2Id':'','type3Id':''});
                    })
                }else if(flag === '1'){
                    this.$nextTick(()=>{
                        this[type].fApi.updateRule('type3Id', {options: []}, true);
                        this[type].fApi.setValue({'type3Id':''});
                    })
                }
                let typeArr = await store.dispatch('user/getMaterialTypeSelect',val);
                this.$nextTick(()=>{
                    this[type].fApi.updateRule(field, {options: typeArr}, true);
                });
            },
            //物资分页
            handlePageChange(page) {
               this.params.pageNum = page;
                this.loadListMaterial(false);
            },
            handleSizeChange(page) {
                this.params.pageSize = page;
                this.loadListMaterial(false);
            },
            //选择物资checkbox
            getRowKeys(row) {
              return row.id
            },
            handleSelectionChange(val) {
              let ids = [];
              val.forEach(item =>{ 
                  ids.push(item)
              });
              this.material.selection = ids;
              this.tis="已选择 "+val.length+" 项";
              if(val.length==0){
                this.tis="";
                this.material.selection = [];
              }
            },
            //提交物资
            materialSubmit(){
                if(this.material.selection.length ==0){
                    return this.$message.error('最少勾选一个物资！');
                }
                //物资列表赋值
               this.material.selection.forEach(item => {
                    item.goodsId = item.id;
                    //item.id = '';
                    this.otherMaterial.tableData.push(item);
                });
                this.materialClassifyTotal();
                
               
                //关闭 清空
                this.material.fApi.resetFields();//清空查询表单
                this.material.visible = false;
                this.$refs.table.clearSelection();
                this.material.selection = [];
                this.tis = "";
            },
            closeMaterial(){
                //关闭 清空
                this.material.fApi.resetFields();//清空查询表单
                this.$refs.table.clearSelection();
                this.material.selection = [];
                this.tis = "";
                 this.material.visible = false;
            },
            //单件合计
            inputPrice(val,row,type){
                if(!val){return;}
                if(!/^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/.test(val)){return;}//只能为数字 小数点两位
                this.materialClassifyTotal();
            },
            materialClassifyTotal(){
                let that = this;
                let countMap = {};
                that.otherMaterial.tableData.forEach(item=>{
                    if(!countMap[item.goodTypeId1]){
                        countMap[item.goodTypeId1] = {
                            priceTotal:0,
                            type1Name:item.type1Name
                        }
                    }
                    if(item.applyNum !== undefined && item.estimatePrice !== undefined){//两个值都有
                        let price = item.estimatePrice * item.applyNum;

                      /*   var str = Number(countMap[item.goodTypeId1].priceTotal) * Number(price);
                        let lastStr = str.toString().split('.');
                        countMap[item.goodTypeId1].priceTotal = lastStr.length === 1 ? str : str.toFixed(2); */

                        let prices = parseFloat(countMap[item.goodTypeId1].priceTotal) + parseFloat(price);
                        if((prices+'').indexOf(".") !== -1){
                            let str = prices.toString().split('.');
                            countMap[item.goodTypeId1].priceTotal = str[1].length === 1 ? prices.toFixed(1) : prices.toFixed(2);
                        }else{
                            countMap[item.goodTypeId1].priceTotal = prices
                        }
                        //countMap[item.goodTypeId1].priceTotal = (prices+'').indexOf(".") !== -1 ? prices.toFixed(2) : prices;
                    }
                    let materialInfo = [];
                    for(var p in countMap){
                        materialInfo.push(countMap[p]);
                    }
                    that.otherMaterial.materialInfo = materialInfo;
                })
            },
            //新增物资
            addOtherMaterial(row){
                let _this = this;
                let index = this.otherMaterial.tableData.findIndex(v=>v.goodsId === row.goodsId);
                let params = {
                    id:'',
                    goodsId:row.goodsId,
                    name:row.name,
                    unit:row.unit,
                    code:row.code,
                    createTime:row.createTime,
                    type1Name:row.type1Name,
                    goodTypeId1:row.goodTypeId1,
                    applyNum:undefined,
                    estimatePrice:undefined,
                    skuInfo:'',
                    add:true,
                    del:true
                }
                this.otherMaterial.tableData.splice(index++,0,params);
                this.keys++;
            },
            //删除物资
            delOtherMaterial(row,index){
                this.$confirm("确认删除", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
                }).then(async () => {
                    this.otherMaterial.tableData.splice(index,1);
                    this.materialClassifyTotal();
                }).catch(() => {});
            },
            resetMaterial(){
                this.material.fApi.resetFields();
                this.loadListMaterial(true);
            },
            //转交人相关操作
            async workflowOpen(){
                const { code,data,msg } = await purchaseApplyUser(2);
                if(code === 200){
                    this.workflow.handleUser = '';
                    this.workflow.workflowList = data;
                    this.workflow.visible = true;
                }
            },
            submitWorkflow(){
                if(!this.workflow.handleUser){
                    return this.$message.error('请选择转交人员！');
                }
                //匹配处理人
                let user = this.workflow.workflowList.find(v=>v.id === this.workflow.handleUser);
                this.workflow.applyUser = user.name;
                this.workflow.visible = false;
            },
            //提交
            async onFormSubmit(formData) {
                this.form.fApi.submit(async (formData, $f) => {
                    try {

                        if(this.otherMaterial.tableData.length === 0){
                            return this.$message.error('请选择物资！');
                        }
                        const arr = this.otherMaterial.tableData;
                        for(var i=0;i<arr.length;i++){
                            if(arr[i].applyNum === undefined || arr[i].applyNum === ''){
                                return this.$message.error('检测到物资第'+(i+1)+'行申请数量未填写！');
                            }
                            if(arr[i].estimatePrice === undefined || arr[i].estimatePrice === ''){
                                return this.$message.error('检测到物资第'+(i+1)+'行预估价未填写！');
                            }
                        }

                        if(!this.workflow.handleUser){
                            return this.$message.error('请选择转交人员！');
                        }

                        let materialTableData = this.otherMaterial.tableData;
                        materialTableData.forEach((v,i)=>{
                            v.id = '';
                            v.sortNum = (i+1);
                            v.estimatePrice =Number(v.estimatePrice) * Number(100);
                            /* v.estimatePrice = (v.estimatePrice * 100)
                            if((v.estimatePrice+'').indexOf(".") !== -1){
                                var str = v.estimatePrice.toString().split('.');
                                v.estimatePrice = str[1].length === 1 ? (v.estimatePrice * 100): (v.estimatePrice * 100);
                            }else{
                                v.estimatePrice = (v.estimatePrice * 100)
                            } */
                        })
                        formData.goodsList = materialTableData;
                        //根据处理人匹配处理人姓名
                        let _obj = this.form.fApi.getRule('projectId').options.find(v=>{ return v.value === formData.projectId});
                        formData.name = _obj.label;
                        formData.handleUser = this.workflow.handleUser;//处理人id
                        //formData.applyUser = this.annxFileUrl;//附件
                        const req =  await purchaseSave(formData);
                        if (req.code == 200) {
                            this.$message.success('新增采购计划成功！');
                            this.onClose();//关闭弹出框
                            this.loadList();//新增成功后刷新列表
                        }
                    } catch (error) {
                        this.$message.info(JSON.stringify(error));
                    }
                })
            },
            loadList() {
                this.$emit("on-search-click", this.params);
            },
            onClose() {
                this.$emit("on-cancel-click",'form');
            }
        }
    };
    </script>
    <style>
        .el-radio{
            margin:10px;
        }
    </style>
    